import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;
import java.util.List;

public class SMJ extends Thread{
	
	private Joystick j;
	private List listeners = new ArrayList();
	private int time;
	
	public SMJ(Joystick j)
	{
		this.j = j;
		time = 0;
	}
	
	// Métodos de registro/desregistro de oyentes
	public synchronized void addVariableNumberChangeListener(VariableChangeListener listener) {
		listeners.add(listener);
	}
		
	public synchronized void removeVariableTimeChangeListener(VariableChangeListener listener) {
		listeners.remove(listener);
	}
		
		
	// Método de notificación de evento
	protected void notifyVariableNumberChanged() {
		List lst;
		EventObject evt = new EventObject(j.getNumber());
		synchronized(this) {
			lst = (List)((ArrayList)listeners).clone();
		}
		
		for (Iterator it = lst.iterator() ; it.hasNext() ; ){
			((VariableChangeListener)it.next()).variableChanged(evt);
		}

	}
	
	public void run()
	{
		while(true)
		{
			
			if(this.time != j.getTime()){
				this.time = j.getTime();
				this.notifyVariableNumberChanged();
			}
			try {
		            Thread.sleep(2000);
            		} catch (Exception e) {
                		System.out.println(e);
            		}
		}
	}

}
